package com.lwg.datastructure.CommonSelectMethod;


/**
 * @author: lwg
 * @Date: 2022/4/23 0:07
 * @Description: 二分查找
 * 首先数组必须是一个有序的数组
 * 1. 循环的终止条件是left<=right
 * 2. 找出中间值，如果和key相等，则直接返回下标
 * 3. 比中间值小，则在左边查找，必中间值大，则在右边查找
 */
public class BinraySearch {
    
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 8, 9};
        System.out.println(binarySearch(arr, 8, 0, arr.length - 1));
    }
    
    private static int binarySearch(int[] arr, int key, int left, int right) {
        // 递归终止条件
        if (left > right) {
            return -1;
        }
        int mid = left + ((right - left) >> 1);
        if (arr[mid] == key) {
            return mid;
        }
        if (arr[mid] > key) {
           return binarySearch(arr, key, left, mid - 1);
        }
        return binarySearch(arr, key, mid + 1, right);
    }
    
}
